package com.ys.controller.api.storage;

import com.alibaba.fastjson.JSON;
import com.ys.config.MenuId;
import com.ys.entity.base.TbFileInfo;
import com.ys.entity.base.TbFileInfoBatchDownload;
import com.ys.entity.base.TpAmazonRegion;
import com.ys.entity.storage.TccLogisticsSadFile;
import com.ys.entity.sys.YsCol;
import com.ys.enume.base.TbFileInfoEnum;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.business.TbFileInfoService;
import com.ys.service.storage.TccLogisticsSadFileService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.util.ToolUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/inter/tccLogisticsSadFile")
public class ApiInterTccLogisticsSadFileController {
	private static final Logger logger = LoggerFactory.getLogger(ApiInterTccLogisticsSadFileController.class);


	@Autowired
	private CommonApiService<TccLogisticsSadFile> commonApiService;

	@Autowired
	private TbFileInfoService tbFileInfoService;

	@Autowired
	private TccLogisticsSadFileService tccLogisticsSadFileService;


	//权限字符
	private final String PERMISSIONS_VIEW = "tccLogisticsSadFile:view";
	private final String PERMISSIONS_DOWNLOAD_BATCH = "tccLogisticsSadFile:downLoadBatch";
	private final String PERMISSIONS_ADD = "tccLogisticsSadFile:add";
	
	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(@ModelAttribute TccLogisticsSadFile cond){
		cond = setSeachSql(cond);
		

		cond.setOrderby("A.Id DESC");
		
		return commonApiService.searchLay(cond);
	}

	@RequestMapping("/searchForModal")
	@ResponseBody
	public LayuiTableVoJA searchForModal(@ModelAttribute TccLogisticsSadFile cond,String vgsbm,String countryCode){
		cond = setSeachSql(cond);

		cond.where("A.vgsbm='"+vgsbm + "' AND A.countryBid='" +countryCode + "'");
		cond.where("A.Id not in (select CbbId from THR_VatApplyDetailCbb WHERE Status != 0)");
		cond.where("A.DeclareState = 0");
		cond.setOrderby("A.Id DESC");

		return commonApiService.searchLay(cond);
	}

	/*
	 * 导出
	 */
	@RequiresPermissions("tccLogisticsSadFile:export")
	@RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TccLogisticsSadFile cond) throws Exception{
		cond = setSeachSql(cond);
		cond.addField("case when A.declareState =0 then '未申报' else '已申报' end as declareStateName");
		cond.setOrderby("A.Id DESC");
		
		cond.setPage(0).setSize(999999);

		List<Map<String, Object>> listData = cond.queryMap();
        
    	List<YsCol> listField = new YsCol()
    			.setMenuId(MenuId.TCC_LogisticsSadFile)
    			.setFrontExport(YsColEnum.FrontExport.SHOW.value)
    			.setOrderby("A.SortNo asc")
    			.queryList();
    	
    	
        ExportExcelUtils<TpAmazonRegion> util = new ExportExcelUtils<TpAmazonRegion>(new TpAmazonRegion());
        
        String toFilePath = util.exportExcel(listData, listField, "C88文件管理");
        UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
        return R.ok(dto.getUrl());
    }

    /**
     * 设置查询的cond的sql设置
     */
    public TccLogisticsSadFile setSeachSql(TccLogisticsSadFile cond){
		cond
			.addLeftJoin("THR_OperateCompanyApply E ON E.Vgsbm = A.Vgsbm")
			.addField("E.Vgsjc vgsjc")
			.addLeftJoin("TS_UserChange F ON F.Id = E.OperatorChangeId")
			.addField("F.UserId + '/' + F.UserName AS createUser")//制单人
			.addField("A.id sourceId")
			.addField("F.UserId operatorUserId")
			.addField("case when A.declareState =0 then '未申报' else '已申报' end as declareStateName");

		;

    	cond = commonApiService.dataAuth(MenuId.TCC_LogisticsSadFile, cond);
		
        return  cond;
    }



	/**
	 * 批量下载文件
	 */
	@RequiresPermissions(PERMISSIONS_DOWNLOAD_BATCH)
	@RequestMapping("/downloadBacth")
	@ResponseBody
	public R downloadBacth(HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, Object> params){
		try {

			//获取数据
			String choooseDatas = params.get("choooseDatas").toString();
			List<Map<String, Object>> detailList = ToolUtil.jsonArrayToList(JSON.parseArray(choooseDatas));
			List<TbFileInfoBatchDownload> downList = new ArrayList<>();
			//遍历数据
			for(Map<String, Object> item:detailList){
				if(item.get("id")!=null && !"".equals(item.get("id"))){
					TbFileInfoBatchDownload tbFileInfoBatchDownload = new TbFileInfoBatchDownload();
					List<TbFileInfo> fileList = new TbFileInfo()
							.setSourceType(TbFileInfoEnum.SourceType.TCC_LogisticsSadFile_AnnexFile.value)
							.setSourceId(Long.parseLong(item.get("id").toString()))
							.setSourceCode("annexFile")
							.queryList();
					if(fileList!=null && fileList.size()>0){
						tbFileInfoBatchDownload.setFileList(fileList);
						if(item.get("fbaNo")!=null && !"".equals(item.get("fbaNo"))){
							tbFileInfoBatchDownload.setFolderName(item.get("fbaNo").toString());
						}
						downList.add(tbFileInfoBatchDownload);
					}
				}
			}
			if(downList.size()>0){
				tbFileInfoService.downLoadFileBatchWithFolder(downList,request, response, "C88文件_"+new Date().toString());
			}else {
				return R.error("没有要下载的文件！");
			}
			return R.ok();
		} catch (Exception e) {
			logger.error("出错：",e.getMessage(),e);
			return R.error(e.getCause().getMessage());
		}
	}

	/**
	 * 新增
	 */
	@RequiresPermissions(PERMISSIONS_ADD)
	@RequestMapping("/toAdd")
	@ResponseBody
	public R toSave(HttpServletRequest request, @RequestParam Map<String, Object> params){
		try {
			//新增
			return tccLogisticsSadFileService.add(params,MenuId.TCC_LogisticsSadFile);
		} catch (Exception e) {
			logger.error("新增出错：",e.getMessage(),e);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return R.error(e.getMessage());
		}
	}

}
